<?php

namespace app\http\middleware;

use app\models\{Admin as Model};

use think\Db;

class Admin
{
    public function handle($request, \Closure $next)
    {
        $id = session('admin_id');
        $admin = (new Model())->where('id', $id)->find();
        $url = $request->baseUrl();
        if (!$admin && $url != '/index/login') {
            return redirect('index/login');
        }
        $auth = config('auth.admin');
        $admin['role'] = explode(',', $admin['role'] ?? '');
        $admin['area'] = explode(',', $admin['area'] ?? '');
        $admin['street'] = explode(',', $admin['street'] ?? '');
        if (!in_array($url, $admin['role']) && !in_array($url, $auth) && $admin['is_default'] == 0) {
            if (request()->isAjax()) {
                exit(json_encode(['code' => 1, 'msg' => '没有操作权限']));
            } else {
                die("<h3 style='color:red;text-align: center; margin-top:200px;'>没有操作权限</h3>");
            }
        }
        $request->admin = $admin;
        return $next($request);
    }
}
